package com.admin.controller;


import com.admin.dto.RolePermissionDto;
import com.admin.entity.Role;
import com.admin.service.PermissionService;
import com.admin.service.RoleService;
import com.admin.utils.Result;
import com.admin.vo.query.RolePermissionVo;
import com.admin.vo.query.RoleQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author szy
 * @since 2023-02-21
 */
@RestController
@RequestMapping("/api/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;

    /*查询角色列表*/
    @GetMapping("/list")
    public Result list(RoleQueryVo roleQueryVo){
        /*创建分页对象*/
        IPage<Role> page = new Page<Role>(roleQueryVo.getPageNo(),roleQueryVo.getPageSize());
        /*调用分页查询方法*/
        roleService.findRoleListByUserId(page,roleQueryVo);
        return Result.ok(page);
    }

    /*添加角色*/
    @PostMapping("/add")
    public Result add(@RequestBody Role role){
        if (roleService.save(role)){
            return Result.ok().message("添加角色成功");
        }else
            return Result.error().message("添加角色失败");
    }

    /*编辑角色*/
    @PutMapping("/update")
    public Result update(@RequestBody Role role){
        if (roleService.updateById(role)){
            return Result.ok().message("角色修改成功");
        }
        return Result.error().message("修改角色失败");
    }


    /*检查角色是否被使用*/
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id){
        if (roleService.hashRoleCount(id)){
            return  Result.exist().message("该角色已分配给其他用户使用，无法删除");
        }
        return Result.ok();
    }

    /*删除角色*/
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        if (roleService.deleteRoleById(id)){
            return Result.ok().message("角色删除成功");
        }
        return  Result.error().message("角色删除失败");
    }

    /*分配权限-查权限*/
    @GetMapping("/getAssignPermissionTree")
    public Result getAssignPermissionTree(Long roleId){
        RolePermissionVo permissionTree = permissionService.findPermissionTree(roleId);
        return Result.ok(permissionTree);
    }

    /*分配权限-保存角色权限信息*/
    @PostMapping("/saveRoleAssign")
    public Result saveRoleAssign(@RequestBody RolePermissionDto rolePermissionDto){
        if (roleService.saveRolePermission(rolePermissionDto.getRoleId(), rolePermissionDto.getList())){
            return Result.ok().message("权限分配成功");
        }
        return Result.error().message("权限分配失败");
    }
}

